<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" size="mini" inline>
      <el-form-item prop="deptId1">
        <treeselect
          v-model="queryParams.deptId1"
          class="tree-select-custom"
          placeholder="请选择所属部门"
          no-results-text="暂无数据匹配"
          no-options-text="暂无数据"
          :normalizer="normalizerDept"
          :options="deptOptions"
          @select="selectDept"
        />
      </el-form-item>
      <el-form-item prop="projectName">
        <el-input v-model.trim="queryParams.projectName" placeholder="请输入成本分期名称" clearable @keyup.enter.native="handleQuery" style="width: 160px" />
      </el-form-item>
      <el-form-item>
        <el-cascader class="cascader-box" v-model="checkedChkitemCode" :options="chkitemTree" placeholder="检查项" :show-all-levels="false" :props="{ multiple: true }" collapse-tags clearable />
      </el-form-item>
      <!-- <el-form-item prop="processType">
        <el-select v-model="queryParams.processType" placeholder="检查项类型" :loading="chkitemTypeLoading" clearable style="width: 120px" @change="onChangeProcessType">
          <el-option v-for="item in chkitemTypeList" :key="item.chkitemCode" :label="item.chkitemName" :value="item.chkitemCode" />
        </el-select>
      </el-form-item>
      <el-form-item prop="chkitemCode">
        <el-select v-model="queryParams.chkitemCode" placeholder="检查项" :loading="firChkLoading" clearable style="width: 120px">
          <p slot="empty" class="el-select-dropdown__empty" style="font-size: 12px; padding: 10px">{{ queryParams.processType ? '无数据' : '请选择检查项类型' }}</p>
          <el-option v-for="item in firChkList" :key="item.chkitemCode" :label="item.chkitemName" :value="item.chkitemCode" />
        </el-select>
      </el-form-item> -->
      <el-form-item prop="progressChkType">
        <el-select v-model="queryParams.progressChkType" placeholder="检查分类" clearable style="width: 120px">
          <el-option v-for="dict in progressChkTypeList" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="rdcType">
        <el-select v-model="queryParams.rdcType" placeholder="检查单位" clearable style="width: 120px">
          <el-option v-for="dict in rdcTypeList" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="isNeed">
        <el-select v-model="queryParams.isNeed" placeholder="筛选考核项目" clearable style="width: 130px">
          <el-option label="全部项目" value="" />
          <el-option label="考核项目" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item prop="isLockout">
        <el-select v-model="queryParams.isLockout" placeholder="是否锁定" clearable style="width: 130px">
          <el-option v-for="dict in yesOrNo" :key="dict.value" :label="`锁定：${dict.label}`" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker v-model="dateRange" type="daterange" value-format="yyyy-MM-dd" range-separator="-" start-placeholder="检查开始日期" end-placeholder="检查结束日期" style="width: 240px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        <el-button icon="el-icon-download" :loading="exportLoading" @click="handleExport" v-if="showBtns.isExport">导出</el-button>
        <el-button @click="$refs.SelectFields.open(dt_selected)">选择展示字段</el-button>
      </el-form-item>
    </el-form>

    <el-table :key="dt_tableKey" v-loading="listLoading" :data="list" size="small">
      <template v-for="i in dt_cols">
        <el-table-column label="检查结果" align="center" min-width="100" key="scoreResultName" v-if="i.value == 'scoreResultName'">
          <el-tag slot-scope="{ row }" size="small" :type="row.showScoreClassName">{{ row.scoreResultName }}</el-tag>
        </el-table-column>
        <el-table-column label="检查单位" align="center" width="100" key="rdcType" v-else-if="i.value == 'rdcType'">
          <dict-tag slot-scope="{ row }" :options="rdcTypeList" :value="row.rdcType" />
        </el-table-column>
        <!-- <el-table-column label="是否考核项目" align="center" width="100" key="isNeed" v-else-if="i.value == 'isNeed'">
          <dict-tag slot-scope="{ row }" :options="yesOrNo" :value="row.isNeed" />
        </el-table-column> -->
        <el-table-column label="是否锁定" align="center" width="100" key="isLockout" v-else-if="i.value == 'isLockout'">
          <dict-tag slot-scope="{ row }" :options="yesOrNo" :value="row.isLockout" />
        </el-table-column>
        <el-table-column v-bind="i" :prop="i.value" :key="i.value" v-else />
      </template>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <SelectFields ref="SelectFields" @selected="onSelectFields" />
  </div>
</template>
<script>
// 项目检查列表
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import auth from '@/plugins/auth'
import { flatList2tree, removeEmptyArray } from '@/utils'
import { yesOrNo, CQ_EVAL_CHKITEM_TYPE as CHKITEM_TYPE } from '@/utils/baseData'
import { treeselect } from '@/api/system/dept'
import { chkitemTypeList, listNextLevel } from '@/api/checkScore/cqEval'
import { pageScores, selectChkitemTree, exportPageScores } from '@/api/statement/trdQc'
import HeaderSelect from '@/views/patrol/components/HeaderSelect'
import { fieldList, rdcTypeList, scoreResultList } from './projectCheckList/fieldList'
import SelectFields from './projectCheckList/SelectFields'
const scoreResult2class = scoreResultList.reduce((o, i) => !void (o[i.value] = i.raw.listClass) && o, {})
export default {
  name: 'ProjectCheckList',
  components: { Treeselect, HeaderSelect, SelectFields },
  dicts: ['cq_progress_chk_type', 'cq_eval_delivery_type'],
  data() {
    return {
      yesOrNo,
      rdcTypeList,
      // Dynamic thead - columns options
      dt_selected: [
        'deptName1',
        'deptName2',
        'deptName3',
        'projectName',
        'phaseName',
        'processName',
        'chkitemName',
        'scoreResultName',
        'progressChkTypeName',
        'rdcType',
        'isNeed',
        'principalUserName',
        'checkDate'
      ],
      dt_cols: [],
      dt_tableKey: 1,

      listLoading: false,
      total: 0,
      list: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId1: undefined,
        projectName: '',
        processType: '',
        // chkitemCode: '',
        progressChkType: '',
        rdcType: '',
        isNeed: '',
        isLockout: ''
      },
      dateRange: [],
      deptOptions: [],
      chkitemTree: [], // 检查项树
      chkitemTreeLoading: false,
      checkedChkitemCode: [],
      chkitemTypeList: [], // 检查项分类
      chkitemTypeLoading: false,
      firChkList: [], // 一级检查项
      firChkLoading: false,
      exportLoading: false
    }
  },
  computed: {
    showBtns() {
      // 操作按钮权限
      const isExport = auth.hasPermi('trdQc:projectCheckList:export')
      return { isExport }
    },
    progressChkTypeList() {
      const list1 = this.dict?.type?.cq_progress_chk_type || []
      const list2 = this.dict?.type?.cq_eval_delivery_type || []
      return [...list1, ...list2]
    }
  },
  created() {
    this.initData()
  },
  methods: {
    initData() {
      treeselect().then(res => (this.deptOptions = res.data))
      this.handleDtSelected()
      this.getList()
      this.getChkitemTree()
    },
    normalizerDept(node) {
      if (!node.children?.length) delete node.children
      return { id: node.fid, label: node.label, children: node.children }
    },
    selectDept(node) {
      this.queryParams.projectName = ''
    },
    async getList() {
      const opt = this.getQuery()
      if (!opt) return

      this.listLoading = true
      const res = await pageScores(opt).catch(() => false)
      this.listLoading = false
      if (res === false) return

      const data = res.rows || []
      data.map(i => {
        // 得分的展示颜色
        i.showScoreClassName = scoreResult2class[i.scoreResult] || 'info'
      })
      this.list = data
      this.total = res.total || 0
    },
    getQuery() {
      const { dateRange, checkedChkitemCode } = this
      const opt = { ...this.queryParams }
      if (Array.isArray(dateRange) && dateRange.length === 2) {
        opt.startTime = dateRange[0]
        opt.endTime = dateRange[1]
      }
      if (checkedChkitemCode?.length) {
        opt.chkitemCodes = checkedChkitemCode.map(arr => arr[arr.length - 1]).join(',')
      }
      return opt
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.checkedChkitemCode = []
      this.handleQuery()
    },
    handleDtSelected() {
      const keys = this.dt_selected
      this.dt_cols = keys.length ? fieldList.filter(i => keys.includes(i.value)) : fieldList
      this.dt_tableKey++
    },
    onSelectFields(selected) {
      this.dt_selected = selected
      this.handleDtSelected()
    },
    async getChkitemTree() {
      this.chkitemTreeLoading = true
      const res = await selectChkitemTree().catch(() => false)
      this.chkitemTreeLoading = false
      if (res === false) return

      let data = res.data || []
      data.map(i => {
        i.label = i.chkitemName
        i.value = i.chkitemCode
      })
      data = flatList2tree(data, { id: 'chkitemId', parent: 'parentId' })
      data = removeEmptyArray(data)

      // 过滤检查项: 工程减分, 品质加/减分
      const filterCode = ['GC-003-001', 'GC-004-001', 'GC-004-002']
      data = data.filter(i => !filterCode.includes(i.chkitemCode))

      this.chkitemTree = data
    },
    async getChkitemTypeList() {
      const opt = {
        // versionCode: '',
        chkitemType: CHKITEM_TYPE.CHKITEMTYPE,
        isEnable: 1
      }
      this.chkitemTypeLoading = true
      const res = await chkitemTypeList(opt).catch(() => false)
      this.chkitemTypeLoading = false
      if (res === false) return

      // 过滤启用且有权访问的检查项
      // let data = res.data || []
      // data = data.filter(i => i.isEnable && i.permCode && auth.hasPermi(`cq:eval:${i.permCode}:list`))
      // this.chkitemTypeList = data
      this.chkitemTypeList = res.data || []
    },
    onChangeProcessType() {
      this.queryParams.chkitemCode = ''
      this.getFirChkList()
    },
    async getFirChkList() {
      const { processType } = this.queryParams
      if (!processType) return (this.firChkList = [])

      this.firChkLoading = true
      const res = await listNextLevel({ chkitemCode: processType }).catch(() => false)
      this.firChkLoading = false
      if (res === false) return (this.firChkList = [])
      this.firChkList = res.data || []
    },
    async handleExport() {
      const opt = this.getQuery()
      if (!opt) return
      if (!this.list.length) return this.msgInfo('暂无数据')

      // 不传分页参数
      delete opt.pageNum
      delete opt.pageSize

      const filename = '项目检查表'
      const res1 = await this.$confirm(`确定导出${filename}?`, '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      this.exportLoading = true
      const res = await exportPageScores(opt).catch(() => false)
      this.exportLoading = false
      if (res === false) return

      const elink = document.createElement('a')
      elink.download = `${filename}_${new Date().Format('yyyyMMdd')}.xlsx`
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(new Blob([res]))
      elink.click()
    }
  }
}
</script>
<style lang="scss" scoped>
.tree-select-custom {
  width: 300px;
  /deep/ {
    .vue-treeselect__control {
      height: 28px;
      font-size: 12px;
    }
    .vue-treeselect__placeholder,
    .vue-treeselect__single-value {
      line-height: 26px;
    }
    .vue-treeselect__input-container,
    .vue-treeselect__input {
      height: 26px;
    }
  }
}
// 级联多选不换行
.cascader-box /deep/ .el-cascader__tags {
  display: flex;
  flex-wrap: nowrap;
  .el-tag:first-child {
    overflow: hidden;
  }
}
</style>
